package cn.aaa.template;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.aaa.config.WechatProperties;
import cn.aaa.domain.OpenIdResult;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class WechatLoginTemplate {
    private WechatProperties properties;
    
    public WechatLoginTemplate(WechatProperties properties) {
        this.properties = properties;
    }
    
    public OpenIdResult getOpenId(String code) {
        //得到要请求的地址
        String sendUrl = String.format(properties.getOpenidurl(), properties.getAppid(), properties.getAppsecret(), code);
        //发送请求
        HttpResponse execute = HttpRequest.get(sendUrl).execute();
        //得到返回结果
        String body = execute.body();//得到的是json字符串
        //将结果转为对象
        OpenIdResult openIdResult = JSON.parseObject(body, OpenIdResult.class);
        String phone = getWechatPhone(code);
        openIdResult.setPhone(phone);
        //只返回了的openid
        return openIdResult;
    }
    
    public String getAccessToken(){
        //得到获取token的路径
        String access_token_url = String.format(properties.getAccesstokenurl(), properties.getAppid(), properties.getAppsecret());
        //执行发送请求
        HttpResponse execute = HttpRequest.get(access_token_url).execute();
        //得到结果
        String body = execute.body();
        //获取里面的token
        return JSON.parseObject(body).get("access_token").toString();
    }
    
    public String getWechatPhone(String code){
        String accessToken = getAccessToken();
        //得到获取token的路径
        String access_token_url = String.format(properties.getPhonenumberurl(), accessToken);
        //执行发送请求
        HttpRequest post = HttpRequest.post(access_token_url);
        //携带请求参数
        Map<String, Object> p = new HashMap<>();
        p.put("code",code);
        post.form(p);
        HttpResponse execute = post.execute();
        //得到结果
        String body = execute.body();
        //获取里面的token
        JSONObject jsonObject = JSON.parseObject(body);
        if(jsonObject.get("errmsg").toString().equals("ok")){
            return JSONObject.parseObject(
                    jsonObject.get("phone_info").toString()
            ).get("phoneNumber").toString();
        }
        //请求失败了就随机一个手机号
        return String.valueOf(Math.abs(new Random().nextLong())).substring(0,11);
    }
}